<?php

	class Settings
	{
		const CACHE_PREFIX = 'settings::';

		private static $local_cache = array();

		public static function get($key, $use_local = true)
		{
			if ($use_local && isset(self::$local_cache[$key])) return self::$local_cache[$key];

			$db    = Database::getInstance();
			$cache = AppCache::getInstance();

			$result = $cache->get(self::CACHE_PREFIX . $key);
			if (is_null($result)) {
				$key_esc = $db->escape($key);
				$result  = $db->one("SELECT `value` FROM `settings` WHERE `key`='{$key_esc}' LIMIT 1");
				$cache->set(self::CACHE_PREFIX . $key, $result);
				self::$local_cache[$key] = $result;
			}

			return $result;
		}

		public static function set($key, $value)
		{
			$db    = Database::getInstance();
			$cache = AppCache::getInstance();

			$key_esc   = $db->escape($key);
			$value_esc = $db->escape($value);

			$db->query("INSERT INTO `settings` SET `key`='{$key_esc}', `value`='{$value_esc}' ON DUPLICATE KEY UPDATE `value`=VALUES(`value`)");
			self::$local_cache[$key_esc] = $value;
			$cache->del(self::CACHE_PREFIX . $key);

			return true;
		}

		public static function __callStatic($name, $arguments)
		{
			if (empty($arguments)) {
				self::get($name);
			} else {
				self::set($name, $arguments[0]);
			}

		}

	}